using System;

namespace Lichtspiel.ECSystem.Behaviors
{
    public abstract class Behavior : IUpdateable
    {
        protected BehaviorHolder holder;
        protected Entity owner;
        protected Action finished;

        protected Behavior() 
            : this(null) {}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="finished">Will be executed after Behavior is finished</param>
        protected Behavior(Action finished) {
            this.finished = finished;
        }

        internal virtual void Initialize(Entity owner, BehaviorHolder holder) {
            this.owner = owner;
            this.holder = holder;

            Initialize();
        }

        /// <summary>
        /// Will be called after Behavior has been added to a Entity and starts running.
        /// </summary>
        protected abstract void Initialize();

        public virtual void Update(GameTime time) { }

        /// <summary>
        /// Only called by Managing Class when Action is finished or stopped.
        /// Overwrite to deinit all contents of action (call base.Stop).
        /// </summary>
        internal virtual void Stop() {
            owner = null;
            holder = null;
            finished = null;
        }

        protected virtual void BehaviorFinished() {
            if (finished != null) {
                finished();
            }

            // parent calls stop and removes this from its list
            if (holder != null) {
                holder.BehaviorFinished(this);
            } else {
                owner.BehaviorFinished(this);
            }
        }
    }
}